layui.define(['zlContext', 'table', 'layer', 'zlConfig', 'tree'], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , table = layui.table
        , layer = layui.layer
        , zlConfig = layui.zlConfig
        , roletree
        , zt = ""
        , table_data = new Array()
        , checkdatas = new Array()
        , selListIds = new Array()
        , tableIns
        , tableSelIns
        , selectionType;
    layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.WM_DRAW, null, function (WParam) {
        if (WParam && $(WParam.elem).attr('class') && $(WParam.elem).attr('class').indexOf('zlPopSourceExt') >= 0) {
            zlPopSourceExt.render($(WParam.elem), $(WParam.elem).value, $(WParam.elem).attr('text'));
        }
    });
    zlPopSourceExt = {
        render: function ($elem, value, text) {
            var showvalue = (value == undefined ? ($elem.attr('value') == undefined ? "" : $elem.attr('value')) : value);
            if ($elem.attr('loaded') && ($elem.attr('value') == undefined ? "" : $elem.attr('value')) == showvalue) {
                return;
            }
            text  = text ? text: '' ;
            var defaultsetting = {
                multselect: true
                , formtitle: "选择树节点"
                , ischeckleaf: false
                , id: 'RWID'
                , sourcedata: undefined
                , edittype: 'edit'
                , check: {
                    enable: false,
                    autoCheckTrigger: true,
                    chkboxType: { "Y": "", "N": "" },
                    chkStyle: "checkbox",
                }
                , view: {
                    showLine: true
                }
                , async: {
                    enable: true,
                    type: 'get',
                    dataFilter: function ajaxDataFilter(treeId, parentNode, responseData) {
                        if (responseData[zlConfig.global.result.statusName] == 'OK') {
                            var data = responseData[zlConfig.global.result.dataName];
                            for (var i = 0; i < data.length; i++) {
                                if (data[i].EXPANDPROPERTY == "org") {
                                    data[i].icon = layui.cache['contentPath'] + "/static/image/org.png";
                                } else {
                                    data[i].icon = layui.cache['contentPath'] + "/static/image/role.png";
                                }
                            }
                            return data;
                        }
                        else {
                            zlContext.errorMsg(responseData[zlConfig.global.result.msgName]);
                        }
                        return responseData;
                    }
                }
                , data: {
                    key: {
                        name: "OBJNAME"
                    }
                    , simpleData: {
                        enable: true
                        , idKey: "RWID"
                        , pIdKey: "SYS_PARENTID"
                        , rootPid: ""
                    }
                }
                , callback: {
                    onAsyncSuccess: function (event, treeId, treeNode, msg) {
                        //zlPopSourceExt.setTrreCheck(treeId, $elem.attr('name'), treesetting);
                    }
                    , onClick: function (event, treeId, treeNode) {
                        zlPopSourceExt.reloadTable(newoptions);
                    }
                }
                ,tabs: [
                    { name: '角色', url: '/kdayun/manager/coreroleauth/queryRole', method: 'get', entryname: 'ROLEID', tableUrl: '/kdayun/admin/coreuser/queryusersbydeptrole', tbmethod: 'post' },
                    { name: '机构部门', url: '/kdayun/manager/coreroleauth/queryOrgddata', method: 'get', tableUrl: '/kdayun/admin/coreuser/queryusersbydeptrole', tbmethod: 'post' }
                ]
                , cols: [[{ type: 'numbers', fixed: 'left', title: '#' },
                { type: 'radio', fixed: 'left' },
                { field: 'OBJNAME', title: '名称', width: 140 },
                { field: 'OBJCODE', title: '编号', width: 140 }
                ]]
                , page: false
                , limit: 20
                , tableismultiple: false
                , max: ''
                , readonly: false
                , verify:''
                , selectcallback: function (treedata, data, norow, options, $this) {

                    if (data == undefined) {
                        return;
                    }
                    if (data.length == 0) {
                        $('input[name="' + options.inputname + '"]').val(data[0][options.name]);
                        $('input[name="' + options.inputhiddename + '"]').val(data[0][options.id]);
                        options.setvalue = data[0][options.id];
                        //$('input[name="' + options.inputtreehiddename + '"]').val(treedata[0][options.id]);
                    } else {
                        var id = ""
                            , name = "";
                        for (var i = 0; i < data.length; i++) {
                            id = id + "," + data[i][options.id];
                            name = name + "," + data[i][options.name];
                        }
                        id = id.substr(1, id.length);
                        name = name.substr(1, name.length);
                        $('input[name="' + options.inputname + '"]').val(name);
                        //$('input[name="' + options.inputtreehiddename + '"]').val(treedata[0][options.id]);
                        $('input[name="' + options.inputhiddename + '"]').val(id);
                        options.setvalue = id;
                    }
                    var noselectid = "";
                    for (var b = 0; b < norow.length; b++) {
                        noselectid = noselectid + "," + norow[b][options.id];
                    }
                    $('input[name="' + options.inputhiddenameno + '"]').val(noselectid);
                }
            }
                , name = $elem.attr('name')
                , inputname = 'input' + name
                , divname = 'div' + name
                , inputhiddename = name
                , inputtreehiddename = 'tree' + name
                , inputhiddenameno = 'no' + name
                , $parent = $elem.parent()
                , options = ($elem.attr('settings') != "" ? eval('(' + $elem.attr('settings') + ')') : {})
                , optionstabs = options.tabs
                , url = optionstabs[0].url
                , placeholder = options.placeholder == undefined ? "" : options.placeholder
                , newoptions
                , addspanid = name + 'addspan'
                , delspanid = name + 'delspan'
                , tempvalue  = options.setvalue ? options.setvalue : value
                , html = [
                    , '<div class = "layui-select-title" name="' + divname + '" >'
                    , '     <input type="text" class="layui-input" placeholder ="' + placeholder + '" name="' + inputname + '" readonly lay-verify="'+options.verify+'"  value="' + text + '">'
                    , '</div>']
                , parenthtml = [
                    , '<input type="hidden" class="layui-input" name="' + inputhiddename + '" value="' + tempvalue + '">'
                    , '<input type="hidden" class="layui-input" name="' + inputtreehiddename + '" value="">'
                    , '<input type="hidden" class="layui-input" name="' + inputhiddenameno + '" value="">'];
            if (url == undefined) {
                zlContext.errorMsg('未找到数据源链接！')
                return;
            }
            $elem.attr('loaded', 1);
            $elem.empty();
            $('input[name="' + inputhiddename + '"]').remove();
            $('input[name="' + inputhiddenameno + '"]').remove();
            $elem.append(html.join(''));
            $parent.append(parenthtml.join(''));
            newoptions = $.extend({}, defaultsetting, options);
            if (newoptions.edittype == 'edit') {
                $('div[name="' + divname + '"]').append(' <i class="layui-icon layui-icon-more layui-i-add" id="' + addspanid + '"></i> ' + '     <i class="layui-icon layui-icon-close layui-i-del" id="' + delspanid + '"></i> ')
            }
            newoptions.async.enable = true;
            newoptions.async.url = url;
            newoptions.async.type = optionstabs[0].method == undefined ? newoptions.async.type : optionstabs[0].method;
            newoptions.async.otherParam = optionstabs[0].params == undefined ? "{}" : optionstabs[0].params;
            newoptions.inputhiddename = inputhiddename;
            newoptions.inputname = inputname;
            newoptions.elemname = name;
            newoptions.inputhiddenameno = inputhiddenameno;
            if (zlContext.isEmpty(text) && !zlContext.isEmpty(value)) {
                if (!zlContext.isEmpty(url)) {
                    var valuelist = new Array()
                        , tempvalue = value;
                    newoptions.async.otherParam = (newoptions.async.otherParam == undefined ? {} : newoptions.async.otherParam)
                    newoptions.async.otherParam[newoptions.id] = tempvalue;
                    $.ajax({
                        url: url,
                        type: newoptions.async.type,
                        async: false,
                        data: newoptions.async.otherParam,
                        dataType: 'json',
                        success: function (result) {
                            var sourcedata = result.obj;
                            for (var i = 0; i < sourcedata.length; i++) {
                                if (tempvalue.indexOf(sourcedata[i][newoptions.id]) > -1) {
                                    objname = objname + "," + sourcedata[i][newoptions.data.key.name]
                                }
                            }
                            objname = objname.substr(1, objname.length);
                            $('input[name="' + inputname + '"]').val(objname);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {

                        },
                        complete: function (XMLHttpRequest, textStatus) {
                        }
                    });
                } else {
                    for (var i = 0; i < newoptions.sourcedata.length; i++) {
                        if (tempvalue.indexOf((newoptions.sourcedata)[i][newoptions.id] > -1)) {
                            objname = objname + "," + (newoptions.sourcedata)[i][newoptions.data.key.name]
                        }
                    }
                    objname = objname.substr(1, objname.length);
                    $('input[name="' + inputname + '"]').val(objname);
                }
            }
            newoptions.async.otherParam = eval('(' + (options.params) + ')');
            if (newoptions.edittype == 'edit') {
                zlPopSourceExt.initspans(newoptions, addspanid, delspanid, divname);
            }
        }

        , initspans: function (options, addspanid, delspanid, divname) {
            var $input = $('input[name="' + options.inputname + '"]');
            $('#' + delspanid).on('click', function () {
                $('.layui-input').val("");
            });
            
            $('#' + delspanid).hide();
            $input.on('mouseenter', function () {
                if ($(this).val() != "") {
                    $('#' + delspanid).show();
                }
            });
            $input.on('mouseleave', function () {
                $('#' + delspanid).hide();
            });
            $('#' + delspanid).on('mouseenter', function () {
                $('#' + delspanid).show();
            });
            $('#' + delspanid).on('mouseleave', function () {
                $('#' + delspanid).hide();
            });
            $('#' + addspanid).on('click', function () {
                var $this = $(this),
                    //获取弹出框拼接内容
                    html = zlPopSourceExt.concatenationStr(options);
                layer.open({
                    type: 1,
                    closeBtn: 1,
                    id: 'zlPopsourceExtLayer',
                    title: options.formtitle == undefined ? "资源信息" : options.formtitle,
                    area: ['1124px', '570px'],
                    content: html.join(''),
                    btn: ['确定', '取消'],
                    success: function (index) {
                        var layercontentH = index.find(".layui-layer-content").height();
                        var seacherbox = $("#seacher-box").height()+parseFloat($("#seacher-box").css('margin-top'));
                        var tabtitleH = $("#tab-title").height();
                        var poptreeboxH = $("#poptree-box");
                        poptreeboxH.height(layercontentH - tabtitleH - seacherbox - 28).css('box-sizing','border-box');
                        tbFileresH = layercontentH - 15;
                        tbSelectedH = layercontentH - 64
                        checkdatas = [];
                        selListIds = [];
                        zt = "";
                        roletree = $.fn.zTree.init($("#" + options.name + "poptree"), options, null);
                        zlPopSourceExt.tabsFun(options);
                        zlPopSourceExt.loadTable(options, tbFileresH);
                        zlPopSourceExt.loadSelTable(options, tbSelectedH);
                        zlPopSourceExt.seacherFun();
                        zlPopSourceExt.keyvalueFun();
                        if ($('#tbFileres').next('div').find(' .layui-table-header th[data-field="1"] input[type="checkbox"]').length > 0) {
                            selectionType = 'checkbox'
                        } else {
                            selectionType = 'radio'
                        }
                        table.on(selectionType + '(tbDatagrid)', function (obj) {
                            var bbb = table.checkStatus('tbFileres').data
                            if (obj.checked == true) {
                                if (selectionType == 'radio') {
                                    checkdatas = [];
                                    checkdatas.push(obj.data);
                                } else {
                                    if (obj.type == 'one') {
                                        checkdatas.push(obj.data);
                                    } else {
                                        for (var i = 0; i < table_data.length; i++) {
                                            checkdatas.push(table_data[i]);
                                        }
                                    }
                                    checkdatas = checkdatas.concat(checkdatas);
                                }
                            } else {
                                if (obj.type == 'one') {
                                    for (var i = 0; i < checkdatas.length; i++) {
                                        if (checkdatas[i][options.id] == obj.data[options.id]) {
                                            checkdatas.remove(i);
                                        }
                                    }
                                    for (var m = 0; m < selListIds.length; m++) {
                                        if (selListIds[m][options.id] == obj.data[options.id]) {
                                            // 如果选中数据为空则已选择列表中选中的数据清空
                                            selListIds.remove(m);
                                        }
                                    }
                                } else {
                                    for (var j = 0; j < table_data.length; j++) {
                                        for (var i = 0; i < checkdatas.length; i++) {
                                            if (checkdatas[i][options.id] == table_data[j][options.id]) {
                                                checkdatas.remove(i);
                                            }
                                        }
                                        // 如果选中数据为空则已选择列表中选中的数据清空
                                        for (var i = 0; i < selListIds.length; i++) {
                                            if (selListIds[i][options.id] == table_data[j][options.id]) {
                                                selListIds.remove(i);
                                            }
                                        }
                                    }

                                }

                            }
                            checkdatas = zlPopSourceExt.diff(checkdatas, options);
                            zlPopSourceExt.reloadSelTable(checkdatas, options);
                        });
                        table.on(selectionType + '(tbSelDatagrid)', function (obj) {
                            if (obj.checked == true) {
                                zt = "1"
                            }
                            selListIds = table.checkStatus('tbSelected').data
                        });
                        // 点击移除事件
                        $("#remove-btn").on('click', function () {
                            zlPopSourceExt.removeFun(checkdatas, options);
                            // 如果选中数据为空则已选择列表中选中的数据清空
                            selListIds = [];
                        });
                    }
                    , resizing: function (index) {
                        var layercontentH = index.find(".layui-layer-content").height();
                        var seacherbox = $("#seacher-box").height();
                        var tabtitleH = $("#tab-title").height();
                        var poptreeboxH = $("#poptree-box");
                        poptreeboxH.height(layercontentH - tabtitleH - seacherbox - 50);
                        tbFileresH = layercontentH - 20;
                        tbSelectedH = layercontentH - 64
                        tableIns.reload({
                            height: tbFileresH
                        });
                        tableSelIns.reload({
                            height: tbSelectedH

                        });
                    }
                    , yes: function (index) {
                        var rows = layui.table.cache['tbSelected']
                            , norow = []
                            , treedata = roletree.getSelectedNodes();
                        if (rows.length == 0) {
                            zlContext.errorMsg(options.errmsg == undefined ? "请选择记录" : options.errmsg);
                            return;
                        } else if (options.max != "" && rows.length > options.max) {
                            zlContext.errorMsg("选择记录大于" + options.max + "条");
                            return;
                        }
                        layer.close(index);
                        if (options.selectcallback != undefined) {
                            options.selectcallback(treedata, rows, norow, options, $this);
                        } else {
                            return rows;
                        }
                    }
                });
            });
        }
        // 默认树和表头的设置
        , initialization: function (options, treeUrl, treeMethod,treeparams) {
            var setting = {
                multselect: true,
                formtitle: "选择树节点",
                ischeckleaf: false,
                id: 'RWID',
                sourcedata: undefined,
                edittype: 'edit',
                check: {
                    enable: false,
                    autoCheckTrigger: true,
                    chkboxType: { "Y": "", "N": "" },
                    chkStyle: "checkbox",
                }
                , view: {
                    showLine: true
                }
                , async: {
                    enable: true,
                    type: treeMethod == undefined ? 'get' : treeMethod,
                    url: treeUrl == undefined ? 'get' : treeUrl,
                    otherParam: treeparams?treeparams:[],
                    dataFilter: function ajaxDataFilter(treeId, parentNode, responseData) {
                        if (responseData[zlConfig.global.result.statusName] == 'OK') {
                            var data = responseData[zlConfig.global.result.dataName];
                            for (var i = 0; i < data.length; i++) {
                                if (data[i].EXPANDPROPERTY == "org") {
                                    data[i].icon = layui.cache['contentPath'] + "/static/image/org.png";
                                } else {
                                    data[i].icon = layui.cache['contentPath'] + "/static/image/role.png";
                                }
                            }
                            return data;
                        }
                        else {
                            zlContext.errorMsg(responseData[zlConfig.global.result.msgName]);
                        }
                        return responseData;
                    }
                }
                , data: {
                    key: {
                        name: "OBJNAME"
                    }
                    , simpleData: {
                        enable: true
                        , idKey: "RWID"
                        , pIdKey: "SYS_PARENTID"
                        , rootPid: ""
                    }
                }
                , callback: {
                    onAsyncSuccess: function (event, treeId, treeNode, msg) {
                        //zlPopSourceExt.setTrreCheck(treeId, $elem.attr('name'), treesetting);
                    },
                    onClick: function (event, treeId, treeNode) {
                        zlPopSourceExt.reloadTable(options);
                    }
                }
                , cols: [[{ type: 'numbers', fixed: 'left', title: '#' },
	                { type: 'checkbox', fixed: 'left' },
	                { field: 'OBJNAME', title: '名称', width: 140 },
	                { field: 'OBJCODE', title: '编号', width: 120 }
	              ]]
                , page: false
                , limit: 10
                , containermultiple: false
            }
            return setting
        }
        //拼接弹出框页面的内容
        , concatenationStr: function (options) {
            // 判断是否配置了tabs
            if (options.tabs.length == 0) {
                zlContext.errorMsg("请配置tabs页签参数！");
                return;
            }
            var objlist = "",
                tabsbox = new Array();
            for (var b = 0; b < options.tabs.length; b++) {
                treeUrl = options.tabs[b].url;
                treeMethod = (options.tabs[b].method == undefined ? 'get' : options.tabs[b].method);
                tableUrl = (options.tabs[b].tableUrl == undefined ? '' : options.tabs[b].tableUrl);
                tableMethod = (options.tabs[b].tbmethod == undefined ? '' : options.tabs[b].tbmethod);
                entryname = (options.tabs[b].entryname == undefined ? '' : options.tabs[b].entryname);
                tableParams = (options.tabs[b].tbparams == undefined ? '' : options.tabs[b].tbparams);
                treeparams = (options.tabs[b].params == undefined ? '' : options.tabs[b].params)
                if (b == 0) {
                    objlist = '<li class="layui-this" lay-url="' + treeUrl + '" lay-tableurl="' + tableUrl + '" lay-tbmethod="' + tableMethod + '" lay-method="' + treeMethod + '" entryname="' + entryname + '" lay-params="' + tableParams + '" lay-treeparams="'+treeparams+'">' + options.tabs[b].name + '</li>'
                } else {
                    objlist = '<li class="" lay-url="' + treeUrl + '" lay-tableurl="' + tableUrl + '" lay-tbmethod="' + tableMethod + '" lay-method="' + treeMethod + '" entryname="' + entryname + '" lay-params="' + tableParams + '" lay-treeparams="'+treeparams+'">' + options.tabs[b].name + '</li>'
                }
                tabsbox.push(objlist);
            }
            html = ['<div id="zlpopSourceext-box" class="layui-fluid" style="height:100%;padding: 0 15px;">'
                , '    <div class="layui-row" style="padding: 10px 0;">'
                , '        <div class="layui-col-xs3">'
                , '            <div id="seacher-box" class="layui-form" style="overflow: hidden; position: relative;">'
                , '                 <input type="text"  placeholder="请输入查找的节点值" id="keyvalue" autocomplete="on" class="layui-input" style="width:100%;float:left;margin-left:0px;height:30px;padding-right: 40px;">'
                , '                 <button class="layui-btn layui-btn-sm layui-btn-normal" id="seacher" style="float:left;height:30px;position: absolute;right: 0;">'
                , '                     <i class="layui-icon">&#xe615;</i>'
                , '                 </button>'
                , '            </div>'
                , '            <div class="layui-card docking-left layui-tab layui-tab-card" style="box-shadow:none;">'
                , '                <ul id="tab-title" class="layui-tab-title">' + tabsbox + '</ul>'
                , '                <div id="poptree-box" class="layui-tab-content" style="height:overflow:auto">'
                , '                    <div id="' + options.name + 'poptree" class="ztree"></div>'
                , '                </div>'
                , '            </div>'
                , '        </div>'
                , '        <div class="layui-col-xs5">'
                , '            <div id="tbFileres-box" class="layui-tab-content" style="padding-top:0;padding-bottom:0">'
                , '                 <table id="tbFileres" class="layui-table fsDatagrid" lay-filter="tbDatagrid" lay-size="sm"></table>'
                , '            </div>'
                , '        </div>'
                , '        <div class="layui-col-xs4">'
                , '            <div class="layui-tab" style="margin:0">'
                , '                <div class="layui-card-header" style="height:22px;line-height:22px;background-color: #f2f2f2;font-size:12px;border:solid 1px #e6e6e6;">已选择</div>'
                , '                <div class="layui-card-header" style="height:22px;line-height:22px;background-color: #f2f2f2;font-size:12px;border:solid 1px #e6e6e6;"><span id="remove-btn" style="cursor: pointer"><i class="layui-icon" style="margin-right: 3px;font-size: 16px;vertical-align: bottom;">&#xe640;</i>移除</span></div>'
                , '                <div id="tbSelected-box">'
                , '                     <table id="tbSelected" class="layui-table fsDatagrid" lay-filter="tbSelDatagrid" lay-size="sm"></table>'
                , '                </div>'
                , '            </div>'
                , '        </div>'
                , '    </div>'
                , '</div>'];
            return html;
        }
        //数据表格渲染
        , loadTable: function (options, tbFileresH) {
            var tbUrl = $(".layui-tab-title li.layui-this").attr("lay-tableurl"),
                tbmethod = $(".layui-tab-title li.layui-this").attr("lay-tbmethod"),
                params = $(".layui-tab-title li.layui-this").attr("lay-params");
            tableIns = table.render({
                elem: '#tbFileres'
                , cellMinWidth: 75
                , height: tbFileresH
                , response: zlConfig.global.gridResponse
                , page: options.page
                , cols: options.cols
                , method: tbmethod
                , limit: options.limit
                , where: params
                , done: function (res, curr, count) {
                    // 设置换页勾选之前的
                    table_data = res.obj;
                    $('.layui-none').width($('.layui-table-header table').width() + 'px');
                    $('.empty-data').width($('.layui-table-body').width() + 'px');
                    zlPopSourceExt.setcheck(res, options, checkdatas);
                }
            });
        }
        //选中数据表格渲染
        , loadSelTable: function (options, tbSelectedH) {
            tableSelIns = table.render({
                elem: '#tbSelected'
                , cellMinWidth: 75
                , height: tbSelectedH
                , cols: options.checkcols == undefined ? options.cols : options.checkcols
                , done: function (res, curr, count) {
                    $('.layui-none').width($('.layui-table-header table').width() + 'px');
                    $('.empty-data').width($('.layui-table-body').width() + 'px');
                }
            });
        }
        //数据列表要重新载入
        , reloadTable: function (options, tbFileresH) {
            var tabsLi = $(".layui-tab-title li.layui-this"),
                sNodes = roletree.getSelectedNodes(),
                paramname = tabsLi.attr('entryname') == undefined ? 'ORGID' : tabsLi.attr('entryname'),
                tabsUrl = tabsLi.attr("lay-tableurl"),
                params = tabsLi.attr("lay-params") == '' ? {} : JSON.parse(tabsLi.attr("lay-params"));
            if (sNodes.length > 0) {
                var paramname1 = sNodes[0].RWID;
                params[paramname] = paramname1;
            } else {
                var paramname1 = "";
                params = "";
            }
            tableIns.reload(
                {
                    url: params == '' ? '' : tabsUrl
                    , page: { curr: 1 }
                	, where: params
                	, response: zlConfig.global.gridResponse
                    , done: function (res, curr, count) {
                        table_data = res.obj;
                        zlPopSourceExt.setcheck(res, options, checkdatas);
                        zlPopSourceExt.checkAll('tbSelected');
                        zlPopSourceExt.setReadonly(options.readonly);
                    }
                });
        }
        //选中数据表格重新载入
        , reloadSelTable: function (selectedData, options, tbSelectedH) {
            if (selectedData.length > 0) {
                for (var i = 0; i < selectedData.length; i++) {
                    if (selectedData[i].LAY_CHECKED != undefined) {
                        delete selectedData[i].LAY_CHECKED
                    }
                }
            }
            tableSelIns.reload({
                data: selectedData
                , done: function (res, curr, count) {
                    // 已选择不需要重新勾选
                    // zlPopSourceExt.selectSetcheck(res, options);
                    // //设置全选checkbox的选中状态
                    // zlPopSourceExt.checkAll('tbSelected');
                    zlPopSourceExt.setReadonly(options.readonly);
                }
            });
        }
        //页签切换树重新请求
        , tabsFun: function (options) {
            $(".layui-tab-title li").on('click', function () {
                selListIds = table.checkStatus('tbSelected').data;
                var treeUrl = $(this).attr("lay-url"),
                    treeMethod = $(this).attr("lay-method"),
                    treeparams = $(this).attr("lay-treeparams"),
                    //创建zTree组件
                    setting = zlPopSourceExt.initialization(options, treeUrl, treeMethod,treeparams);
                roletree = $.fn.zTree.init($("#" + options.name + "poptree"), setting, null);
                zlPopSourceExt.reloadTable(options);
            })
        }
        // 搜索按钮事件
        , seacherFun: function () {
            $('#seacher').on('click', function () {
                var text = $('#keyvalue').val();
                zlPopSourceExt.searchNode(text);
            });
        }
        // 搜索输入框回车事件
        , keyvalueFun: function () {
            $("#keyvalue").keydown(function () {
                var e = event || window.event;
                if (e.keyCode == 13) {
                    var text = $('#keyvalue').val();
                    zlPopSourceExt.searchNode(text);
                }
            });
        }
        //搜索节点事件
        , searchNode: function (value) {
            var keyType = "OBJNAME";
            if (value === "") {
                var allNode = roletree.transformToArray(roletree.getNodes());
                roletree.showNodes(allNode);
                return;
            }
            nodeList = roletree.getNodesByParamFuzzy(keyType, value);
            nodeList = roletree.transformToArray(nodeList);
            zlPopSourceExt.updateNodes(true, value, keyType);
        }
        //搜索完更新树内容
        , updateNodes: function (highlight, value, keyType) {
            var allNode = roletree.transformToArray(roletree.getNodes());
            roletree.hideNodes(allNode);
            for (var n = 0; n < nodeList.length; n++) {
                zlPopSourceExt.findParent(roletree, nodeList[n]);
            }
            roletree.showNodes(nodeList);
            nodeList = roletree.getNodesByParamFuzzy(keyType, value);
            for (var i = 0; i < nodeList.length; i++) {
                roletree.updateNode(nodeList[i]);

            }
        }
        // 查找父级节点
        , findParent: function (zTree, node) {
            zTree.expandNode(node, true, false, false);
            var pNode = node.getParentNode();
            if (pNode != null) {
                nodeList.push(pNode);
                zlPopSourceExt.findParent(zTree, pNode);
            }
        }
        // 已选列表移除事件
        , removeFun: function (checkdatas, options) {
            // 获取移除选中的数据
            var checkdata = table.checkStatus('tbSelected').data;
            if (checkdata.length == 0) {
                zlContext.errorMsg(options.errmsg == undefined ? "请选择记录" : options.errmsg);
                return
            }
            //添加去掉勾选状态
            zt = "1"
            table.deleteCheckRows('tbSelected');
            for (var i = 0; i < checkdatas.length; i++) {
                for (var j = 0; j < checkdata.length; j++) {
                    if (checkdatas[i][options.id] == checkdata[j][options.id]) {
                        checkdatas.splice(i, 1)
                    }
                }
            }
            zlPopSourceExt.reloadTable(options);
        }
        //数据表格进来设置已选中的数据
        , setcheck: function (res, options, recorddata) {
            if (res.state != 'OK') {
                return;
            }
            if (options.setvalue != undefined) {
                var ids = options.setvalue
            } else {
                var ids = $('input[name="' + options.inputhiddenameno + '"]').val()
            }
            res = res.obj;
            if (ids != undefined) {
                for (var i = 0; i < res.length; i++) {
                    if (ids.indexOf(res[i][options.id]) > -1 && zt == "") {
                        recorddata.push(res[i]);
                        res[i]['LAY_CHECKED'] = 'true';
                        var index = res[i]['LAY_TABLE_INDEX'];
                        var el = $('#tbFileres');
                        zlPopSourceExt.checkStyle(el, index);
                    }
                    if (recorddata.length > 0) {
                        for (var n = 0; n < recorddata.length; n++) {
                            if (res[i][options.id] == recorddata[n][options.id]) {
                                res[i]['LAY_CHECKED'] = 'true';
                                var index = res[i]['LAY_TABLE_INDEX'];
                                var el = $('#tbFileres');
                                zlPopSourceExt.checkStyle(el, index);
                            }
                        }
                    }
                }
            }
            layui.form.render();
            //设置全选checkbox的选中状态
            zlPopSourceExt.checkAll('tbFileres');
            recorddata = zlPopSourceExt.diff(recorddata, options);
            zlPopSourceExt.reloadSelTable(recorddata, options);
        }
        //已选中的数据打勾选状态
        , selectSetcheck: function (res, options) {
            if (res == undefined || res.count == 0) {
                return;
            }
            if (options.setvalue != undefined) {
                var ids = options.setvalue
            } else {
                var ids = $('input[name="' + options.inputhiddename + '"]').val()
            }
            res = res.data
            if (ids != undefined) {
                for (var i = 0; i < res.length; i++) {
                    if (ids.indexOf(res[i][options.id]) > -1 && zt == "") {
                        res[i]['LAY_CHECKED'] = 'true';
                        var index = res[i]['LAY_TABLE_INDEX'];
                        var el = $('#tbSelected');
                        zlPopSourceExt.checkStyle(el, index);
                    }
                    if (selListIds.length > 0) {
                        for (var n = 0; n < selListIds.length; n++) {
                            if (res[i][options.id] == selListIds[n][options.id]) {
                                res[i]['LAY_CHECKED'] = 'true';
                                var index = res[i]['LAY_TABLE_INDEX'];
                                var el = $('#tbSelected');
                                zlPopSourceExt.checkStyle(el, index);
                            }
                        }
                    }
                }
            }
            layui.form.render();
            //设置全选checkbox的选中状态
            zlPopSourceExt.checkAll('tbSelected');
        }
        //设置选中样式
        , checkStyle: function (el, index) {
            if (selectionType == "radio") {
                el.next('div').find('.layui-table-fixed-l tr[data-index=' + index + '] input[type="radio"]').prop('checked', true);
                el.next('div').find('.layui-table-fixed-l tr[data-index=' + index + '] .layui-form-radio').addClass('layui-form-radioed');
                el.next('div').find('.layui-table-fixed-l tr[data-index=' + index + '] .layui-anim').addClass('layui-anim-scaleSpring');
            } else {
                el.next('div').find('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                el.next('div').find('.layui-table-fixed-l tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
            }
        }
        //判断全选状态
        , checkAll: function (obj) {
            var checkStatus = table.checkStatus(obj);
            if (checkStatus.isAll) {
                $('#' + obj).next('div').find(' .layui-table-header th[data-field="1"] input[type="checkbox"]').prop('checked', true);
                $('#' + obj).next('div').find('.layui-table-header th[data-field="1"] input[type="checkbox"]').next().addClass('layui-form-checked');
                layui.form.render();
            }
        }
        //设置只读的时候不可编辑
        , setReadonly: function(readonlystate){
        	if(readonlystate){
        		if(selectionType == "checkbox"){
        			$(".layui-table-header").find("input[name = 'layTableCheckbox'][lay-filter='layTableAllChoose']").each(function () {
                        $(this).attr("disabled", 'disabled');
                    });
                    $(".layui-table-body.layui-table-main").find("input[name='layTableCheckbox']").each(function () {
                        $(this).attr("disabled", 'disabled');
                    });
                    $(".layui-table-fixed.layui-table-fixed-l").find(".layui-table-body").find("input[name='layTableCheckbox']").each(function () {
                        $(this).attr("disabled", 'disabled');
                    });
        		}else{
        			$(".layui-table-body.layui-table-main").find("input[type='radio']").each(function () {
                        $(this).attr("disabled", 'disabled');
                    });
                    $(".layui-table-fixed.layui-table-fixed-l").find(".layui-table-body").find("input[type='radio']").each(function () {
                        $(this).attr("disabled", 'disabled');
                    });
        		}
                layui.form.render();
        	}
        }
        //数组去重
        , diff: function (arr, options) {
            if (arr.length == 0) {
                var res = arr;
            } else {
                var res = [arr[0]];
                for (var i = 1; i < arr.length; i++) {
                    var repeat = false;
                    for (var j = 0; j < res.length; j++) {
                        if (arr[i][options.id] == res[j][options.id]) {
                            repeat = true;
                            break;
                        }
                    }
                    if (!repeat) {
                        res.push(arr[i]);
                    }
                }
            }
            return res;
        }
        // 只弹出框选择，不赋值
        , onlyshow: function (options, requestEvent) {
            options.inputhiddenameno = 'no'+options.name;
            var html = zlPopSourceExt.concatenationStr(options),
                treeUrl = options.tabs[0].url,
                treeMethod = options.tabs[0].method,
                treeparams = options.tabs[0].params,
                //创建zTree\和table组件
                setting = zlPopSourceExt.initialization(options, treeUrl, treeMethod,treeparams)
            options = $.extend({}, setting, options);
            
            layer.open({
                type: 1,
                closeBtn: 1,
                id: 'zlPopsourceExtMessLayer',
                title: options.formtitle == undefined ? "资源信息" : options.formtitle,
                area: ['1124px', '570px'],
                content: html.join(''),
                btn: ['确定', '取消'],
                success: function (index) {
                    $("#zlpopSourceext-box").append('<input type="hidden" class="layui-input" name="' + options.inputhiddenameno + '" value="">');
                    var layercontentH = index.find(".layui-layer-content").height();
                    var seacherbox = $("#seacher-box").height();
                    var tabtitleH = $("#tab-title").height();
                    var poptreeboxH = $("#poptree-box");
                    poptreeboxH.height(layercontentH - tabtitleH - seacherbox - 53);
                    tbFileresH = layercontentH - 20;
                    tbSelectedH = layercontentH - 69
                    checkdatas = [];
                    selListIds = [];
                    zt = "";
                    roletree = $.fn.zTree.init($("#" + options.name + "poptree"), options, null);
                    zlPopSourceExt.tabsFun(options);
                    zlPopSourceExt.loadTable(options, tbFileresH);
                    zlPopSourceExt.loadSelTable(options, tbSelectedH);
                    zlPopSourceExt.seacherFun();
                    zlPopSourceExt.keyvalueFun();
                    if ($('#tbFileres').next('div').find(' .layui-table-header th[data-field="1"] input[type="checkbox"]').length > 0) {
                        selectionType = 'checkbox'
                    } else {
                        selectionType = 'radio'
                    }
                    table.on(selectionType + '(tbDatagrid)', function (obj) {
                        if (obj.checked == true) {
                            if (selectionType == 'radio') {
                                checkdatas = [];
                                checkdatas.push(obj.data);
                            } else {
                                if (obj.type == 'one') {
                                    checkdatas.push(obj.data);
                                } else {
                                    for (var i = 0; i < table_data.length; i++) {
                                        checkdatas.push(table_data[i]);
                                    }
                                }
                                checkdatas = checkdatas.concat(checkdatas);
                            }
                        } else {
                            if (obj.type == 'one') {
                                for (var i = 0; i < checkdatas.length; i++) {
                                    if (checkdatas[i][options.id] == obj.data[options.id]) {
                                        checkdatas.remove(i);
                                    }
                                }
                                for (var m = 0; m < selListIds.length; m++) {
                                    if (selListIds[m][options.id] == obj.data[options.id]) {
                                        // 如果选中数据为空则已选择列表中选中的数据清空
                                        selListIds.remove(m);
                                    }
                                }
                            } else {
                                for (var j = 0; j < table_data.length; j++) {
                                    for (var i = 0; i < checkdatas.length; i++) {
                                        if (checkdatas[i][options.id] == table_data[j][options.id]) {
                                            checkdatas.remove(i);
                                        }
                                    }
                                    // 如果选中数据为空则已选择列表中选中的数据清空
                                    for (var i = 0; i < selListIds.length; i++) {
                                        if (selListIds[i][options.id] == table_data[j][options.id]) {
                                            selListIds.remove(i);
                                        }
                                    }
                                }

                            }

                        }
                        checkdatas = zlPopSourceExt.diff(checkdatas, options);
                        if (selectionType != 'radio') {
                            //zlPopSourceExt.reloadTable(options);
                        }
                        zlPopSourceExt.reloadSelTable(checkdatas, options);
                    });
                    table.on(selectionType + '(tbSelDatagrid)', function (obj) {
                        if (obj.checked == true) {
                            zt = "1"
                        }
                        selListIds = table.checkStatus('tbSelected').data
                    });
                    // 点击移除事件
                    $("#remove-btn").on('click', function () {
                        zlPopSourceExt.removeFun(checkdatas, options);
                        // 如果选中数据为空则已选择列表中选中的数据清空
                        selListIds = [];
                    });
                }
                , resizing: function (index) {
                    var layercontentH = index.find(".layui-layer-content").height();
                    var seacherbox = $("#seacher-box").height();
                    var tabtitleH = $("#tab-title").height();
                    var poptreeboxH = $("#poptree-box");
                    poptreeboxH.height(layercontentH - tabtitleH - seacherbox - 53);
                    tbFileresH = layercontentH - 20;
                    tbSelectedH = layercontentH - 69

                    tableIns.reload({
                        height: tbFileresH
                    });
                    tableSelIns.reload({
                        height: tbSelectedH
                    });
                }
                , yes: function (index) {
                    var rows = layui.table.cache['tbSelected'];
                    if (rows.length == 0) {
                        zlContext.errorMsg(options.errmsg == undefined ? "请选择记录" : options.errmsg);
                        return;
                    }
                    requestEvent(rows)
                    layer.close(index);
                }
                , end: function (index) {
                    $("#zlpopSourceext-box").find('input[name="'+options.inputhiddenameno+'"]').remove();
                }
            });

        }
    }
    //删除数组自定义函数
    , Array.prototype.remove = function (dx) {
        if (isNaN(dx) || dx > this.length) { return false; }
        for (var i = 0, n = 0; i < this.length; i++) {
            if (this[i] != this[dx]) {
                this[n++] = this[i]
            }
        }
        this.length -= 1
    }
    exports('zlPopSourceExt', zlPopSourceExt);
});